package com.running.base.run.jms.sender;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.IOException;
import java.security.PrivilegedAction;

@Component
@ConditionalOnProperty(value = "jms.param", havingValue = "true")
public class JMSSender {

    private static final Logger logger = LoggerFactory.getLogger(JMSSender.class);

    @Resource
    private WeblogicSecurityBeanSender weblogicSecurityBeanSender;

    @Resource(name = "jmsTemplateSender")
    private JmsTemplate jmsTemplate;

    private final String to_jms_queue = "jn_fd_queue";

    public void sendJmsXmlContent(String content) throws IOException {

        final MessageCreator messageCreator = new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                logger.info("jms发送消息={}", content);
                return session.createTextMessage(content);
            }
        };

        //now publish the message as the authenticated user
        weblogicSecurityBeanSender.runPrivilegedActionAsSubject(new PrivilegedAction() {
            @Override
            public Object run() {
                jmsTemplate.send(to_jms_queue, messageCreator);
                return null;
            }
        });
    }


}